<template>
  <van-row>
    <!-- 身份证正面 -->
    <van-col :span="24">
      <van-row class="idcard_front_panel">
        <img
          v-if="!cardFrontShow"
          class="back"
          :src="require('../../assets/images/idcard_front.png')"
        />

        <img v-if="cardFrontShow" class="back" :src="cardFrontFile" />
        <van-row class="idcard_front_content">
          <van-col :span="7"></van-col>
          <van-col :span="10" align="center">
            <div class="addIconDiv">
              <input type="file" id="logimg" v-on:change="uploadIDCardFront" accept="image/*" />
              <van-icon color="#1989FA" size="1rem" name="plus"></van-icon>
            </div>
            <span>上传身份证正面照</span>
          </van-col>
          <van-col :span="7"></van-col>
        </van-row>
      </van-row>
    </van-col>
    <!-- 身份证反面 -->
    <van-col :span="24">
      <van-row class="idcard_front_panel">
        <img
          v-if="!cardBackShow"
          class="back"
          :src="require('../../assets/images/idcard_back.png')"
        />
        <img v-if="cardBackShow" class="back" :src="cardBackFile" />
        <van-row class="idcard_front_content">
          <van-col :span="7"></van-col>
          <van-col :span="10" align="center">
            <div class="addIconDiv">
              <input type="file" id="logimg" v-on:change="uploadIDCardBack" accept="image/*" />
              <van-icon color="#1989FA" size="1rem" name="plus"></van-icon>
            </div>
            <span>上传身份证反面照</span>
          </van-col>
          <van-col :span="7"></van-col>
        </van-row>
      </van-row>
    </van-col>

    <!-- <van-uploader ref="uploader" :after-read="getReadFile" v-show="false" /> -->

    <van-dialog v-model="show" title="信息核验" :showConfirmButton="false">
      <van-form>
        <van-field v-model="frontInfo.address" label="住址" />
        <van-field v-model="frontInfo.idNumber" label="身份证号" />
        <van-field v-model="frontInfo.birthday" label="出生日期" />
        <van-field v-model="frontInfo.name" label="姓名" />
        <van-field v-model="frontInfo.sex" label="性别" />
        <van-field v-model="frontInfo.nation" label="民族" />
        <van-field v-model="frontInfo.failureTime" label="签发日期" />
        <van-field v-model="frontInfo.issueTime" label="失效日期" />
        <van-field v-model="frontInfo.issuanceAuthority" label="签发机关" />
        <van-row>
          <van-button class="leftbtn" type="default" native-type="submit">提交</van-button>
          <van-button class="rightbtn" type="default" @click="onCacel">取消</van-button>
        </van-row>
      </van-form>
    </van-dialog>
  </van-row>
</template>

<script>
export default {
  name: 'IdcardOCR',
  data() {
    return {
      access_token: '',
      side: '',
      show: false,
      frontInfo: {},
      cardFrontShow: false,
      cardBackShow: false,
      cardFrontFile: '',
      cardBackFile: ''
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    initData() {
      //  获取Access Token
      let clientId = 'kEftSfS4a6b9wcZG7deUgaEc'
      let client_secret = 'sPo95ZGR2I3P9M4NNreg7hm05azte4li'
      let url = `/aip/oauth/2.0/token?grant_type=client_credentials&client_id=${clientId}&client_secret=${client_secret}&`
      this.postJson(url).then((res) => {
        console.log('res', res)
        this.access_token = res.access_token
      })
    },
    //图片转64
    // getBase64Img(img) {
    //   var canvas = document.createElement('canvas')
    //   canvas.width = img.width
    //   canvas.height = img.height
    //   var ctx = canvas.getContext('2d')
    //   ctx.drawImage(img, 0, 0, img.width, img.height)
    //   var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
    //   var dataURL = canvas.toDataURL('image/' + ext)
    //   return dataURL
    // },
    //压缩
    compress(img) {
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      // 瓦片canvas
      let tCanvas = document.createElement('canvas')
      let tctx = tCanvas.getContext('2d')
      let initSize = img.src.length
      let width = img.width
      let height = img.height
      // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      let ratio
      if ((ratio = (width * height) / 4000000) > 1) {
        console.log('大于400万像素')
        ratio = Math.sqrt(ratio)
        width = width / ratio
        height = height / ratio
      } else {
        ratio = 1
      }
      canvas.width = width
      canvas.height = height
      //        铺底色
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      // 如果图片像素大于100万则使用瓦片绘制
      let count
      if ((count = (width * height) / 1000000) > 1) {
        console.log('超过100W像素')
        count = ~~(Math.sqrt(count) + 1) // 计算要分成多少块瓦片
        //            计算每块瓦片的宽和高
        let nw = ~~(width / count)
        let nh = ~~(height / count)
        tCanvas.width = nw
        tCanvas.height = nh
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            )
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height)
      }
      // 进行最小压缩
      let ndata = canvas.toDataURL('image/jpeg', 0.1)
      console.log('压缩前：' + initSize)
      console.log('压缩后：' + ndata.length)
      console.log(
        '压缩率：' + ~~((100 * (initSize - ndata.length)) / initSize) + '%'
      )
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0
      return ndata
    },
    /*
     * 上传身份证正面照
     */
    uploadIDCardFront(e) {
      // console.log(e.target.files[0])
      // if (e.target.files[0].size > 204800) {
      //   this.$toast.fail('请将图片压缩到200KB以下')
      //   return
      // }
      var image = new Image()
      image.src = window.URL.createObjectURL(e.target.files[0])
      // console.log(image)
      image.onload = () => {
        // console.log(this.getBase64Img(image))
        this.cardFrontFile = this.compress(image)
        this.cardFrontShow = true
        this.side = 'front'
        console.log('641')
        this.getReadFile(this.cardFrontFile, this.side)
      }
    },

    /**
     * 上传身份证反面照e
     */
    uploadIDCardBack(e) {
      // if (e.target.files[0].size > 204800) {
      //   this.$toast.fail('请将图片压缩到200KB以下')
      //   return
      // }
      var image = new Image()
      image.src = window.URL.createObjectURL(e.target.files[0])
      // console.log(image)
      image.onload = () => {
        // console.log(this.getBase64Img(image))
        this.cardBackFile = this.compress(image)
        this.cardBackShow = true
        this.side = 'back'
        console.log('642')
        this.getReadFile(this.cardBackFile, this.side)
      }
    },
    /**
     * 获取上传文件
     */
    getReadFile(file, side) {
      // console.log('1')
      // console.log(file)
      //调用第三方接口识别图片
      let url = '/aip/rest/2.0/ocr/v1/idcards?access_token=' + this.access_token
      let params = {
        id_card_side: side,
        image: file
      }
      // console.log('this.side', side)
      this.post(url, params).then((res) => {
        if (side == 'front') {
          this.frontInfo.address = res.words_result.住址.words
          this.frontInfo.idNumber = res.words_result.公民身份号码.words
          this.frontInfo.birthday = res.words_result.出生.words
          this.frontInfo.name = res.words_result.姓名.words
          this.frontInfo.sex = res.words_result.性别.words
          this.frontInfo.nation = res.words_result.民族.words
        }
        if (side == 'back') {
          this.frontInfo.failureTime = res.words_result.签发日期.words
          this.frontInfo.issueTime = res.words_result.失效日期.words
          this.frontInfo.issuanceAuthority = res.words_result.签发机关.words
        }
        this.isShow()
        console.log(this.frontInfo)
      })
    },
    isShow() {
      if (
        this.frontInfo.address != null &&
        this.frontInfo.idNumber != null &&
        this.frontInfo.birthday != null &&
        this.frontInfo.name != null &&
        this.frontInfo.sex != null &&
        this.frontInfo.nation != null &&
        this.frontInfo.failureTime != null &&
        this.frontInfo.issueTime != null &&
        this.frontInfo.issuanceAuthority != null
      )
        this.show = true
    },
    /**
     * 表单提交
     */
    onSubmit() {
      this.show = false
    },
    onCacel() {
      this.show = false
    }
  }
}
</script>

<style lang="less" scoped>
#logimg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 100;
}
.idcard_front_panel {
  height: 4.5rem;
  position: relative;
  overflow: hidden;
  margin-bottom: 0.5rem;
  .back {
    width: 100%;
    height: 100%;
    position: absolute;
    // z-index: 1;
    opacity: 0.4;
  }
  .idcard_front_content {
    position: relative;
    top: 1.2rem;
    .addIconDiv {
      width: 1.3rem;
      padding: 0.3rem;
      border: dashed 3px #1989fa;
      border-radius: 20%;
      margin-bottom: 0.5rem;
      opacity: 1;
    }
    span {
      font-weight: 600;
    }
  }
  /deep/ .uploaderClz {
    width: 100%;
    height: 100%;
    /deep/ .van-uploader__input-wrapper {
      width: 100%;
      height: 100%;
    }
  }
}
.leftbtn {
  width: 50%;
  float: left;
}
.rightbtn {
  width: 50%;
  float: right;
}
</style>